package com.ruoyi.yipaiju.controller;


import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.page.TableDataApi;
import com.ruoyi.common.enums.dict.DiligenceReportOrderStatus;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.yipaiju.WeChatPayConfig;
import com.ruoyi.yipaiju.domain.DiligenceReportOrder;
import com.ruoyi.yipaiju.service.IDiligenceReportOrderService;
import com.ruoyi.yipaiju.service.IWechatPayService;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.cipher.Signer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayResponse;
import com.wechat.pay.java.service.payments.model.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 尽调订单
 */
@RestController
@RequestMapping("/wechat/pay")
public class WeChatPayController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(WeChatPayController.class);

    @Autowired
    private IDiligenceReportOrderService diligenceReportOrderService;

    @Autowired
    private IWechatPayService wechatPayService;
    @Autowired
    private WeChatPayConfig wechatPayConfig;


    /**
     * 生成尽调订单
     * @param productId 产品id
     * @param openid openid
     * @param foreclosedId 房源id
     * @return
     * @throws Exception
     */
    @PostMapping("/unifiedorder")
    public Map<String, String> unifiedOrder(@RequestParam int productId,
                                            @RequestParam String openid, @RequestParam Long foreclosedId) throws Exception {

        String outTradeNo = "S"+productId+"O"+ System.currentTimeMillis();
        PrepayResponse response = wechatPayService.createJsapiOrder(productId, openid, outTradeNo, foreclosedId);

        log.info("微信支付下单响应: {}", response);

        // 3. 构造签名字符串
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String nonceStr = IdUtils.generateNonceStr();
        String packageStr = "prepay_id=" + response.getPrepayId();

        Map<String, String> result = new HashMap<>();
        result.put("appId", wechatPayConfig.getAppId());
        result.put("timeStamp", timestamp);
        result.put("nonceStr", nonceStr);
        result.put("package", packageStr);
//        result.put("signType", "MD5");
        result.put("signType", "RSA");
//        String paySign = generateJsapiPaySign(wechatPayConfig.getAppId(), response.getPrepayId(),
//                wechatPayConfig.getMchId(), wechatPayConfig.getMerchantSerialNumber(),
//                wechatPayConfig.getPrivateKey(), wechatPayConfig.getApiV3Key());


        // 1. 创建自动管理证书的配置
        RSAAutoCertificateConfig config = new RSAAutoCertificateConfig.Builder()
                .merchantId(wechatPayConfig.getMchId())
                .merchantSerialNumber(wechatPayConfig.getMerchantSerialNumber())
                .privateKey(wechatPayConfig.getPrivateKey())
                .apiV3Key(wechatPayConfig.getApiV3Key())
                .build();

        // 2. 从配置中获取签名器
        Signer signer = config.createSigner();

        String message = String.format("%s\n%s\n%s\n%s\n",
                wechatPayConfig.getAppId(), timestamp, nonceStr, packageStr);

        // 4. 生成签名
        String paySign = signer.sign(message).getSign();

        result.put("paySign", paySign);
        result.put("outTradeNo", outTradeNo);

        return result;
    }


    /**
     * 支付通知
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/notify")
    public String payNotify(HttpServletRequest request) throws Exception {
        try {
            // 解析回调数据
            Transaction transaction = wechatPayService.handleCallback(request);
            // 处理业务逻辑
            String outTradeNo = transaction.getOutTradeNo();
            String transactionId = transaction.getTransactionId();
            String tradeState = transaction.getTradeState().name();
            log.info("微信支付回调通知: {}", transaction);

            DiligenceReportOrder diligenceReportOrder = diligenceReportOrderService.selectOneDiligenceReportOrder(Builder.of(DiligenceReportOrder::new).with(DiligenceReportOrder::setOutTradeNo, outTradeNo).build());
            diligenceReportOrder.setStatus(DiligenceReportOrderStatus.SUCCESS.getValue());
            diligenceReportOrder.setTransactionId(transactionId);
            diligenceReportOrderService.updateDiligenceReportOrder(diligenceReportOrder);
            diligenceReportOrderService.sendTeplateMessage(diligenceReportOrder, "正在为您生成报告，请稍后...");
            new Thread(() -> {
                // TODO: 根据支付结果更新订单状态等业务逻辑
                if (diligenceReportOrder != null) {
                    boolean pdf = diligenceReportOrderService.createPdf(diligenceReportOrder);
                    if (pdf){
                        // TODO 发消息
                        diligenceReportOrderService.sendTeplateMessage(diligenceReportOrder, "您的尽调报告已生成，详情请点击查看");
                        diligenceReportOrder.setStatus(DiligenceReportOrderStatus.RESUCESS.getValue());

                    }else {
                        diligenceReportOrder.setStatus(DiligenceReportOrderStatus.REFAIL.getValue());
                    }
                }
                diligenceReportOrderService.updateDiligenceReportOrder(diligenceReportOrder);
            }).start();
            // 返回成功响应
            return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        } catch (Exception e) {
            // 返回失败响应
            return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>";
        }
    }

    @GetMapping("/query")
    public Transaction query(@RequestParam String outTradeNo) throws Exception {
        return wechatPayService.queryOrder(outTradeNo);
    }

    /**
     * 获取尽调报告集合
     * @return
     * @throws Exception
     */
    @GetMapping("/query-order-list")
    public TableDataApi queryOrderList(){
        return getTableApi(wechatPayService.queryOrderList());
    }


}
